package com.lizemin.filter;

import cn.hutool.json.JSONUtil;
import com.lizemin.resp.ApiResponse;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

import static org.springframework.cloud.gateway.filter.NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER;

/**
 * @author lzm
 * @date 2025/4/19 22:36
 * @description 全局异常过滤器，用于统一结果封装
 */
@Component
public class GlobalExceptionFilter implements GlobalFilter, Ordered {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        log.info("请求路径为：{}", path);

        return chain.filter(exchange);
//        ServerHttpResponseDecorator decorator = wrapResponse(exchange);
//        return chain.filter(exchange.mutate().response(decorator).build());
    }

    private static ServerHttpResponseDecorator wrapResponse(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        DataBufferFactory bufferFactory = response.bufferFactory();
        return new ServerHttpResponseDecorator(response) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                getStatusCode();
                // 获取微服务的响应状态码
                HttpStatus statusCode = getStatusCode();
                if (!statusCode.is2xxSuccessful()) {
                    return super.writeWith(body);
                }
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                    return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                        // 如果响应过大，会进行截断，出现乱码，看api DefaultDataBufferFactory
                        // 有个join方法可以合并所有的流，乱码的问题解决
                        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                        DataBuffer dataBuffer = dataBufferFactory.join(dataBuffers);
                        // 响应内容
                        byte[] content = new byte[dataBuffer.readableByteCount()];
                        dataBuffer.read(content);
                        // 释放掉内存
                        DataBufferUtils.release(dataBuffer);
                        // responseData就是response的值，就可查看修改了
                        String responseData = new String(content, StandardCharsets.UTF_8);
                        // 重置返回参数
                        String result = JSONUtil.toJsonStr(ApiResponse.success(responseData));
                        log.info("网关的响应结果为：{}", result);
                        byte[] uppedContent = result.getBytes(StandardCharsets.UTF_8);
                        HttpHeaders headers = response.getHeaders();
                        headers.setContentLength(uppedContent.length);
                        headers.setContentType(MediaType.APPLICATION_JSON);
                        response.setStatusCode(HttpStatus.OK);
                        // 设置响应内容
                        return bufferFactory.wrap(uppedContent);
                    }));
                }
                return super.writeWith(body);
            }
        };
    }

    // 这里的顺序很重要，要不然不会走自己自定义的响应过滤器
    @Override
    public int getOrder() {
        return WRITE_RESPONSE_FILTER_ORDER - 2;
    }

}



